<?php 
class Zen_Behavior_Alias extends Zen_Behavior_Model {
	
	public function beforeCreate($params){
		$params = $this->prepareCreateUpdate($params);
		return $params;
	}
	
	public function beforeUpdate($params){
		$params = $this->prepareCreateUpdate($params);
		return $params;
	}
	
	protected function prepareCreateUpdate($params){
		//Подготовить псевдоним
		if ( isset($params['alias']) && $params['alias']=='' ) {
			$alias = $params['label'];
			$alias = $this->prepareAlias($alias);
			$model = $this->getModel();
			$id = $params['id'];
			//Подготовка уникальности псевдонима
			if ($model instanceof Zen_List) {
				$i = 1;
				$and = ( $id ) ? " and id!=$id" : '';
		    	$el = $model->select()->getOne("`alias`='$alias' $and");
		    	$alias_base = $alias;
		    	while ($el) {
		    		$alias=preg_replace('/\_\d$/','',$alias);
		    		$alias = $alias_base."_".$i;
		    		$i++;
		    		$el = $model->select()->getOne("`alias`='$alias' $and");
		    	}
			}
			$params['alias'] = $alias;
		} 		
		return $params;
	}
	
	protected function prepareAlias($alias) {
		$filter = new Zen_Filter_Alias();
		$alias = $filter->filter($alias);
		$alias = trim($alias);
		return $alias;
	}
	
}